package com.example.dell.fastshopping.user.address;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.dell.fastshopping.MainActivity;
import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.network.http.BaseResponse;
import com.example.dell.fastshopping.utils.KLog;
import com.example.dell.fastshopping.utils.RegexUtils;
import com.example.dell.fastshopping.utils.ToastUtils;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ${YSH} on 2019/4/24.
 * 描述        ${TODO}
 * <p>
 * 更新者       $author$
 * 更新时间     $Data$
 * 描述         ${TODO}
 */
public class AddAddressActivity extends AppCompatActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.address_head)
    TextView addressHead;
    @BindView(R.id.detial_address)
    EditText detialAddress;
    @BindView(R.id.set_default)
    ImageView setDefault;
    @BindView(R.id.save)
    TextView save;
    private AddressViewMolder molder;
    private MyAddress myAddress;
    private AddressEntity addressEntity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {

        Intent intent = getIntent();
        myAddress = (MyAddress) intent.getSerializableExtra("entity");
        if (myAddress == null) {
            title.setText("添加地址");
        } else {
            title.setText("编辑地址");
            this.name.setText(myAddress.getUserName());
            this.phone.setText(myAddress.getPhone());
            this.addressHead.setText(myAddress.getArea());
            this.detialAddress.setText(myAddress.getAddress());
            int defaults = myAddress.getDefaults();

            if (defaults == 0) {
                this.setDefault.setTag("0");
                this.setDefault.setImageDrawable(getResources().getDrawable(R.mipmap.unselect));
            } else {
                this.setDefault.setTag("1");
                this.setDefault.setImageDrawable(getResources().getDrawable(R.mipmap.select));
            }

        }

        molder = ViewModelProviders.of(this).get(AddressViewMolder.class);
        addressEntity = molder.getAddress(this);

    }

    private void showLocation() {
        if (addressEntity == null) {
            ToastUtils.showShort("获取失败");
            return;
        }
        final List<String> provinceList = addressEntity.getProvinceList();
        final List<List<String>> cityList = addressEntity.getAllCityList();
        final List<List<List<String>>> arealList = addressEntity.getAllArealList();
        Resources resources = getResources();
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                String province = provinceList.get(options1);
                String city = cityList.get(options1).get(option2);
                String areal = arealList.get(options1).get(option2).get(options3);
                if (province.equals(city)) {
                    addressHead.setText(city + "-" + areal);
                } else {
                    addressHead.setText(province + "-" + city + "-" + areal);
                }
            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setTitleText("城市选择")//标题/
                .setSubCalSize(18)//确定和取消文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleColor(resources.getColor(R.color.text_black))//标题文字颜色
                .setSubmitColor(resources.getColor(R.color.myRed))//确定按钮文字颜色
                .setCancelColor(resources.getColor(R.color.myGrey))//取消按钮文字颜色
                .setTitleBgColor(resources.getColor(R.color.myGrey2))//标题背景颜色 Night mode
                .setBgColor(resources.getColor(R.color.white))//滚轮背景颜色 Night mode
                .setContentTextSize(18)//滚轮文字大小
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(0, 0, 0)  //设置默认选中项
                .setOutSideCancelable(true)//点击外部dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .build();

        pvOptions.setPicker(provinceList, cityList, arealList);
        pvOptions.show();

    }

    private void addAddress() {

        String name = this.name.getText().toString().trim();
        if (name.isEmpty()) {
            ToastUtils.showShort("请填写姓名");
            return;
        }

        String phone = this.phone.getText().toString().trim();
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showShort("请检查手机号码");
            return;
        }

        String addressHead = this.addressHead.getText().toString().trim();
        String addressDetial = this.detialAddress.getText().toString().trim();
        if (addressHead.isEmpty() || addressDetial.isEmpty()) {
            ToastUtils.showShort("请检查地址是否为空");
            return;
        }

        int tag = Integer.valueOf((String) this.setDefault.getTag());

        if (myAddress == null) {
            molder.addAddress(name, addressHead, phone, addressDetial, tag).observe(this, new Observer<BaseResponse>() {
                @Override
                public void onChanged(@Nullable BaseResponse baseResponse) {
                    if (baseResponse.isSuccess()) {
                        finish();
                    }
                }
            });
        } else {

            myAddress.setUserName(name);
            myAddress.setArea(addressHead);
            myAddress.setPhone(phone);
            myAddress.setAddress(addressDetial);
            myAddress.setDefaults(tag);
            molder.editAddress(myAddress).observe(this, new Observer<BaseResponse>() {
                @Override
                public void onChanged(@Nullable BaseResponse baseResponse) {
                    if (baseResponse.isSuccess()) {
                        finish();
                    }
                }
            });
        }

    }

    @OnClick({R.id.back, R.id.save, R.id.set_default, R.id.address_head})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.save:
                addAddress();
                break;
            case R.id.set_default:
                setDefaultImg(view);
                break;
            case R.id.address_head:
                showLocation();
                break;
        }
    }

    private void setDefaultImg(View view) {
        int tag = Integer.valueOf((String) this.setDefault.getTag());
        if (tag == 1) {
            this.setDefault.setImageDrawable(getResources().getDrawable(R.mipmap.unselect));
            this.setDefault.setTag("0");
        } else {
            this.setDefault.setImageDrawable(getResources().getDrawable(R.mipmap.select));
            this.setDefault.setTag("1");
        }
    }
}
